package me.vudu.Conflict.util;

import org.getspout.spoutapi.gui.GenericLabel;
import org.getspout.spoutapi.gui.Label;
 
public class WrappedGenericLabel extends GenericLabel {
 
    @Override
    public Label setText(String text) {
        if (text != null && !getText().equals(text)) {
            if (GenericLabel.getStringWidth(text, this.scale) >= this.getWidth()) {
                int spaceSpace = GenericLabel.getStringWidth(" ");
                int spaceAvailable = this.getWidth();
                int spaceRemaining = spaceAvailable;
                String[] words = text.split(" ");
                String finalText = "";
             
                for (int i=0; i<words.length; i++) {
                    int wordSpace = GenericLabel.getStringWidth(words[i]);
 
                    if (!finalText.isEmpty() && wordSpace>spaceRemaining) {
                        finalText += "\n";
                        spaceRemaining = spaceAvailable;
                    }
                    finalText += words[i];
                    spaceRemaining -= wordSpace;
                    if (spaceSpace>spaceRemaining) {
                        finalText += "\n";
                        spaceRemaining = spaceAvailable;
                    } else {
                        finalText += " ";
                        spaceRemaining -= spaceSpace ;
                    }
                }
                super.setText(finalText);
            } else {
                super.setText(text);
            }
        }
        return this;
    }
}